//
//  CFRMRecipeListController.swift
//  CrazyFatReducingMeal
//
//  Created by iOS-Czz on 2023/11/8.
//

import UIKit

class CFRMRecipeListController: CFRMBaseViewController {
   
    lazy var viewModel: CFRMRecipeViewModel = {
        return CFRMRecipeViewModel()
    }() 
    lazy var collectionView: UICollectionView = {
        let waitItemWidth = (Screen_Width - 45) / 2
        let waitItemSize = CGSize(width: waitItemWidth, height: 315)
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = waitItemSize
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.sectionInset = UIEdgeInsets(top: 15, left: 15, bottom: 0, right: 15)
        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        view.delegate = self
        view.dataSource = self
        view.register(UINib(nibName: "CFRMRecipeListCell", bundle: .main), forCellWithReuseIdentifier: "CFRMRecipeListCell")
//        CFRMRecipeListCell
        return view
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addRightBarButton(imageName:"icon_add")
        self.view.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        // Do any additional setup after loading the view.
    }
    override func clockRightBarButtonAction() {
        self.navigationController?.pushViewController(CFRMAddRecipeController(), animated: true)
    }
    
    func loadData(){
        self.viewModel.getPageData() { models in
            self.collectionView.reloadData()
        }
        
    }
}
extension CFRMRecipeListController:UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel.dataSource.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:CFRMRecipeListCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CFRMRecipeListCell", for: indexPath) as! CFRMRecipeListCell
        cell.model = self.viewModel.dataSource[indexPath.item]
        cell.clickEditBlock = { [self] in
            let editVC = CFRMAddRecipeController()
            editVC.model = self.viewModel.dataSource[indexPath.item]
            editVC.isEdit = true
            self.navigationController?.pushViewController(editVC, animated: true)
        }
        return cell
    }
}
